package com.crazy.controller.common;

import static com.crazy.common.constants.HttpConstants.CACHE_CONTROL;
import static com.crazy.common.constants.HttpConstants.EXPIRES;
import static com.crazy.common.constants.HttpConstants.NO_CACHE;
import static com.crazy.common.constants.HttpConstants.PRAGMA;
import static com.crazy.security.ValidateCodeBean.CONTENTTYPE;
import static com.crazy.security.ValidateCodeBean.VALIDCODE;

import java.io.OutputStream;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.crazy.security.ValidateCodeBean;

/**
 * 生成验证码控制器
 * 
 * @author zhangweiwei
 * @since 2013-9-16下午1:59:08
 */
@Controller
public class ValidateCodeController {
	@Inject
	private ValidateCodeBean bean;

	/**
	 * 生成验证码
	 * 
	 * @author Zhang Weiwei
	 * @since 2013-9-25下午9:08:09
	 */
	@RequestMapping("/validCode")
	public void validCode(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setHeader(CACHE_CONTROL, NO_CACHE);
		response.setHeader(PRAGMA, NO_CACHE);
		response.setDateHeader(EXPIRES, 0);
		response.setContentType(CONTENTTYPE);
		try (OutputStream os = response.getOutputStream()) {
			String text = bean.generate(os);
			HttpSession session = request.getSession();
			session.setAttribute(VALIDCODE, text);
		}
	}
}
